<?php
/**
 * @Author: rocky
 * Date: 2019/9/28
 * Time: 11:22
 */


namespace app\shop\controller\api\v1;


use app\common\controller\BaseApiController;
use app\shop\model\ShopGoods;
use app\shop\model\ShopGoodsCate;
use app\common\tools\FilterSearch;
use app\shop\model\ShopGoodsSpec;
use app\shop\model\ShopSeckillActivity;
use app\shop\model\ShopSpell;
use app\shop\resource\GoodListResource;
use app\shop\resource\InviteSpellResource;
use app\shop\resource\PtUserResoure;
use think\db\Query;

/**
 * 商品
 * Class Goods
 * @package app\shop\controller\api\v1
 */
class Goods extends BaseApiController
{
    /*
     * 获取商品分类
     */
    public function getCate()
    {
        $pid = $this->request->get('pid');
        $data = ShopGoodsCate::when($pid, function ($q) use ($pid) {
            $q->where('pid', $pid);
        }, function ($q) {
            $q->where('pid', 0);
        })->where('status', 1)->field('id,title,img')->where('is_deleted', 0)->select();
        $this->successCode($data);
    }

    /*
     * 商品列表
     */
    public function postList()
    {
        $sale_order = $this->request->post('sale_order', false);
        $price_order = $this->request->post('price_order', false);
        $filter = new FilterSearch(new ShopGoods());
        $data = $filter->like('title', 'post')
            ->eq('cate_id', 'post')
            ->findIn('tags_id', 'post')
            ->query()->when($sale_order, function (Query $q) use ($sale_order) {
                $q->removeOption('order')->order("specs_sum");
            })
            ->when($price_order, function (Query $q) use ($price_order) {
                $q->removeOption('order')->order("price");
            })
            ->withSum('specs', 'sale')
            ->pages()->where('is_deleted', 0)->select();
        $this->successCode(GoodListResource::collection($data));
    }

    /*
     * 拼团用户列表
     */
    public function getSpellUser()
    {
        $good_id = $this->request->get('good_id');
        $data = ShopSpell::with(['user'])->where('status', 1)->where('good_id', $good_id)->pages()->select();
        $this->successCode(PtUserResoure::collection($data));
    }

    //邀请好友拼团
    public function getSpellInvite()
    {
        $data = ShopSpell::get($this->request->id, ['good', 'order.user']);
        self::successCode(InviteSpellResource::item($data));
    }

    /*
     * 商品详情
     */
    public function getDetail()
    {
        $id = $this->request->get('id');
        $seckill_id = $this->request->get('seckill_id', 0);
        $seckill_type = $this->request->get('seckill_type', 1);
        $type = $this->request->get('type', 0);
        $data = ShopGoods::field('id,title,mini_title,image,taget_url,price,adv_img,content,spec')
            ->withSum(['specs' => 'sale_count'], 'sale')
            ->withSum(['specs' => 'stock_count'], 'stock')
            ->withSum(['cart' => 'cart_count'], 'num')
            ->append(['is_collect'])->where('is_deleted', 0)
            ->withAttr(['price' => function ($val, $data) use ($type) {
                $spec = ShopGoodsSpec::where('gid', $data['id'])->removeOption('order')->order('price')->find();
                if ($type == 0) {
                    return $spec['price'];
                } elseif ($type == 1) {
                    return $spec['seckill_price'];
                } elseif ($type == 2) {
                    return $spec['spell_price'];
                }
            }])
                ->find($id);
        if (empty($data)) {
            $this->errorCode(100, '商品不存在');
        }
        if ($seckill_type == 1) {
            $data['activity_time'] = ShopSeckillActivity::where('id', $seckill_id)->value('end_time');
        } else {
            $data['activity_time'] = ShopSeckillActivity::where('id', $seckill_id)->value('start_time');
        }
        $data['refund_sale_text'] = sysconf('refund_sale_text|raw');
        $data['customer_tel'] = sysconf('customer_tel');
        $goods = ShopGoods::where('type', 2)->removeOption('order')->orderRand()->withSum('specs', 'sale')->limit(4)->select();
        $data['goods'] = GoodListResource::collection($goods);
        $data['spec'] = $this->spec($data['spec']);
        $this->successCode($data);
    }

    public function postSpec()
    {
        $good_id = $this->request->post('good_id');
        $spec_group = $this->request->request('spec_group');
        $data = ShopGoodsSpec::where('gid', $good_id)->where('spec_group', $spec_group)->field('id,price_market,price,stock,sale,thumb')->find();
        $this->successCode($data);
    }

    /**
     * 返回规格组合
     * @Author: rocky
     * 2019/9/29 9:26
     * @param $specs
     * @return array
     */
    protected function spec($specs)
    {
        $specs = json_decode($specs, true);
        $specList = [];
        if (!empty($specs)) {
            $specArrs = explode(',', $specs[0]);
            foreach ($specArrs as $specArr) {
                $specValue = explode(':', $specArr);
                $group_name = $specValue[0];
                $specList[]['group_name'] = $group_name;
            }
            foreach ($specs as $key => $spec) {
                $specArrs = explode(',', $spec);

                foreach ($specArrs as $k => $specArr) {
                    $specValue = explode(':', $specArr);

                    $group_name = $specValue[0];
                    $val = $specValue[1];

                    if ($specList[$k]['group_name'] == $group_name) {
                        if (!in_array($val, $specList[$k]['value'])) {
                            $specList[$k]['value'][] = $val;
                        }
                    }
                }

            }
        }
        return $specList;
    }
}